package adsi.server;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.json.*;

import javazoom.upload.*;
import java.util.*;

public class UploadServlet extends HttpServlet {

    private String directory = "/tmp";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String filename = request.getParameter("filename");
            String controller = request.getParameter("controller");
            if (MultipartFormDataRequest.isMultipartFormData(request)) { // Uses MultipartFormDataRequest to parse the HTTP request.
                filename = System.currentTimeMillis() + ".csv";
                UploadBean upBean = new UploadBean();
                upBean.setFolderstore(directory);
                upBean.setOverwrite(true);
                upBean.setWhitelist("*.csv,*.txt");
                upBean.setFilesizelimit(12800);
                MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
                if (mrequest != null) {
                    controller = mrequest.getParameter("controller");
                }
                if (controller != null) {
                    Hashtable files = mrequest.getFiles();
                    if (files != null && !files.isEmpty()) {
                        UploadFile file = (UploadFile) files.get("uploadfile");
                        if (file != null) {
                            file.setFileName(filename);
                        }
                        upBean.store(mrequest, "uploadfile"); // Uses the bean now to store specified by jsp:setProperty at the top.
                    }
                }
                response.sendRedirect("upload" + controller + ".jsp?filename=" + filename + "&data=" + getFileDataInJSON(filename, controller));
            } else if (filename != null && controller != null) {
                JSONArray list = new JSONArray(getFileDataInJSON(filename, controller));
                if ("Maintenances".equals(controller)) {
                    MaintenancesLogic.createMany(list);
                } else if ("Equipments".equals(controller)) {
                    EquipmentsLogic.createMany(list);
                } else if ("Lines".equals(controller)) {
                    LinesLogic.createMany(list);
                }
                out.println("true");
            }
        } catch (Exception e) {
            System.out.println("mesa " + e.getMessage());
            e.printStackTrace();
            out.println("{ 'ERROR' : 'Archivo corrupto' }");
        } finally {
            out.close();

        }
    }

    private String getFileDataInJSON(String filename, String controller) throws IOException, JSONException {
        BufferedReader in = new BufferedReader(new FileReader(directory + "/" + filename));
        JSONArray list = new JSONArray();
        JSONObject obj;
        String[] maintenances = {"description", "duration"};
        String[] equipments = {"tail-number", "drop-date", "available-date", "delivered"};
        String[] lines = {"description", "drop-date", "available-date"};
        String line, dataVector[], controllerVector[] = {};

        if ("Maintenances".equals(controller)) {
            controllerVector = maintenances;
        } else if ("Equipments".equals(controller)) {
            controllerVector = equipments;
        } else if ("Lines".equals(controller)) {
            controllerVector = lines;
        }

        line = in.readLine(); //header line
        while ((line = in.readLine()) != null) { //content lines
            dataVector = line.split(",");
            if (controllerVector.length == dataVector.length) {
                obj = new JSONObject();
                for (int i = 0; i < dataVector.length; i++) {
                    obj.put(controllerVector[i], dataVector[i]);
                }
                if (obj.length() > 0) {
                    list.put(obj);
                }
            }
        }
        in.close();
        
        return list.toString();
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
// </editor-fold>
}
